<template>
  <van-popup v-model="show" @close="closePopup" @open="openPopup" position="bottom" :class="'vipPay_Popup'">
    <div class="vipPay_box">
      <ul class="vipPay_menu">
        <!-- <li class="vip_level3" :class="{'active':activeLevel == 3}" @click="tabCheckedFn(3)" btn>
          <i class="bg_mask"></i>
          <div class="vm_text">
            <i class="vip_icon"></i>
            <strong>体验版</strong>
            <span>当前</span>            
          </div>
        </li> -->
        <li class="vip_level5" :class="{'active':activeLevel == 5}" @click="tabCheckedFn(5)" btn>
          <div class="level5_box">
            <!-- <i class="bg_mask"></i> -->
            <span class="vip_v">个人版</span>
            <div class="vm_text">
              <i class="vip_icon"></i>
              <strong>SVIP</strong>
              <!-- <span>当前</span> -->
            </div>
          </div>
          <span class="level_sale">限时特惠</span>
        </li>
        <li class="vip_level4" :class="{'active':activeLevel == 4}" @click="tabCheckedFn(4)" btn>
          <i class="bg_mask"></i>
          <span class="vip_v">企业版</span>
          <div class="vm_text">
            <i class="vip_icon"></i>
            <strong>VIP</strong>
            <!-- <span>当前</span> -->
          </div>
        </li>
        <li class="vip_level1" :class="{'active':activeLevel == 1}" @click="tabCheckedFn(1)" btn>
          <i class="bg_mask"></i>
          <span class="vip_v">企业版</span>
          <div class="vm_text">
            <i class="vip_icon"></i>
            <strong>SVIP</strong>
            <!-- <span>当前</span> -->
          </div>
        </li>
        <li class="vip_level2" :class="{'active':activeLevel == 2}" @click="tabCheckedFn(2)" btn>
          <i class="bg_mask"></i>
          <span class="vip_v">企业版</span>
          <div class="vm_text">
            <i class="vip_icon"></i>
            <strong>Plus</strong>
            <!-- <span>当前</span>             -->
          </div>
        </li>
      </ul>
      <div class="vipPay_main">
        <div class="vip_month_box" :class="{'two_m':monthData && monthData.length == 2}">
          <template v-if="monthData">
            <template v-for="item,idx in monthData">
              <div class="vip_month_item" @click="monthCheckedFn(item)" :class="{'active':monthIndex == item.duration,'disabled':!item.status}" :key="'month'+idx" btn>
                <div class="vmb_month">{{item.duration}}个月</div>
                <div class="vmb_price">￥<strong>{{item.payAmount}}</strong></div>
                <div class="vmb_day_price" v-if="activeLevel == 5">{{item.dayPrice}}/天</div>
                <div class="vmb_original_price" v-else>￥{{item.marketPrice}}</div>
                <div class="give_month">{{item.give?'赠送'+item.give:activeLevel == 5?'限时特惠':'紧急试用'}}</div>
                <i class="discounts_icon" v-if="item.disCount">限时{{(item.disCount*10).toFixed(1)}}折起</i>
              </div>
            </template>
          </template>
        </div>
        <div class="vip_endtime" v-if="activePayObj">有效期至：{{activePayObj.endTime}}</div>
        <!-- 支付方式选择 -->
        <ul class="pay_type" v-if="!$isWX">
          <li :class="{'active':activePayType == 1}" @click="activePayType=1">
            <div class="ml_left">
                <i class="ml_icon weixin"></i>
                <span>微信</span>
            </div>
            <div class="ml_right">
              <i class="checked_icon"></i>
            </div>
          </li>
          <li :class="{'active':activePayType == 2}" @click="activePayType=2">
            <div class="ml_left">
                <i class="ml_icon zfb"></i>
                <span>支付宝</span>
            </div>
            <div class="ml_right">
              <i class="checked_icon"></i>
            </div>
          </li>
        </ul>
        <!-- 支付按钮 -->
        <div class="pay_btn" btn :class="{'disabled':btnDisabled,'wxPayBtn':$isWX}" @click="goPay">{{btnName}}</div>
        <div class="function_box">
          <!-- <router-link :to="{path:'/moreEquity',query:{vLevel:activeLevel}}">查看权益详情</router-link>
          <router-link :to="{path:'/contactQR'}">联系客服</router-link> -->
          <span @click="goPage({path:'/moreEquity',query:{vLevel:activeLevel}})" btn>查看权益详情</span>
          <span @click="goPage({path:'/contactQR'})" btn>联系客服</span>
        </div>
        <!-- <ul class="more_list">
          <li btn>
            <router-link :to="{path:'/contactQR'}">
              <div class="li_box">
                <div class="ml_left">
                    <i class="ml_icon contact"></i>
                    <span>联系客服</span>
                </div>
                <div class="ml_right">
                  <i class="arrow"></i>
                </div>
              </div>
            </router-link>
          </li>
          <li btn>
            <router-link :to="{path:'/moreEquity',query:{vLevel:activeLevel}}">
              <div class="li_box">
                <div class="ml_left">
                    <i class="ml_icon jurisdiction"></i>
                    <span>权益详情</span>
                </div>
                <div class="ml_right">
                  <span>更多权益</span>
                  <i class="arrow"></i>
                </div>
              </div>
            </router-link>
          </li>
        </ul> -->
      </div>
    </div>
    <van-dialog v-model="isShowUpDialog" :showConfirmButton="false" :class="'up_dialog'">
      <div class="up_dialog_content">
        <h5>温馨提示</h5>
        <div class="up_dialog_msg">
          <p v-if="userVipInfo">您当前会员级别为：<strong>{{vipLevelName(userVipInfo.vipLevel)}}{{renewInit(userVipInfo)}}</strong></p>
          <p>您将要开通：<strong>{{vipLevelName(activeLevel)}}</strong></p>
        </div>
        <div class="up_dialog_btns">
          <button @click="isShowUpDialog=false">取 消</button>
          <button class="active" @click="upConfirmFn">确 定</button>
        </div>
      </div>
      <p class="up_annotation">注：开通后当前级别仍在生效中，级别高的会员将优先使用</p>
    </van-dialog>
  </van-popup>
</template>

<script>
export default {
  name: 'buyVipPopup',
  data() {
    return {
      activePayType: 1, //支付方式 - 1:微信，2支付宝
      activeLevel: 5,  //当前选中的vip等级
      userDetail: null, //用户信息
      cancelRequest: null, //清除上一次请求
      monthData: null, //月份数据list
      activePayObj: null, //最终支付状态数据
      monthIndex: 12, //月份选择（默认12个月）
      userLevel:'',  //当前用户等级
      btnName:'',
      btnDisabled:false,
      paySign:'', //签名
      orderDataObj:null,  //接口返回的接口订单数据
      orderId:'', //订单id
      show:false,
      parentVueObj:null,
      routerObj:null,
      isShowUpDialog:false,
      userVipInfo:null, //用户续费信息
    };
  },
  created() {
  },
  mounted() {
  },
  methods: {

    initUserLevel(){
      if(this.minLeve){ //如果当前功能有最低权限等级则定位到该vip等级选项，否则定位到比当前会员等级高一个等级的会员
        // this.activeLevel = this.minLeve == 3 ? 4 : this.minLeve == 1 ? 5 : this.minLeve; //如果是体验版，则定位到vip
        // if(this.minLeve == 3){   //最低权限是体验版，则定位到vip
        //   this.activeLevel = 4;
        // }else if(this.minLeve == 1){ //最低权限是SVIP，则定位到SVIP个人版
        //   this.activeLevel = 5;
        // }else{
        //   this.activeLevel = this.minLeve;
        // }
        this.activeLevel = this.minLeve;
        console.log('当前弹框最低会员等级',this.activeLevel);
      }else{
        let cacheLevel = localStorage.getItem('vipLevel');
        if(cacheLevel == '0' || cacheLevel == '3'){
          this.activeLevel = 4;  //VIP版  根据缓存等级高一级判断位置（现在是vip为最低付费等级）
        }else if(cacheLevel == '4' || cacheLevel == '5'){
          this.activeLevel = 1;  //SVIP个人版 根据缓存等级高一级判断位置
        }else{
          this.activeLevel = 2;  //PLUS  根据缓存等级高一级判断位置
        }
      }
    },
    goPage(pms){
      this.show = false;
      // location.href=pms.path;
      this.routerObj.push(pms);
    },
    closePopup(){
      if(this.close) this.close();  //关闭时的回调
    },
    openPopup(){
      if(this.open) this.open();  //打开时的回调
      this.routerObj = this.obj;
    },
    upConfirmFn(){  //升级确认弹框点击确认
      this.pays();
    },
    goPay(){  //点击支付按钮
      if(!this.btnDisabled){ //不置灰，则可以去支付
        let uLevel = this.initVipLevel(this.userLevel);
        let cLevel = this.initVipLevel(this.activeLevel);
        if(cLevel > uLevel && this.userLevel != '0'){  //升级会员的情况（免费版开通会员不弹出）
          // this.isShowUpDialog = true;
          this.getRenewal();
        }else{
          this.pays();
        }
      }
    },
    getRenewal() {
      this.$axios.get("/api/pay/GetAutoRenewInfo").then(res => {
        if(res.data.code == '0'){
          this.userVipInfo = res.data.data;
          this.isShowUpDialog = true;
        }
      });
    },
    pays(){ //支付函数
      if(this.$isWX){ //微信端内支付
        this.wxJSAPIPay();
      }else{  //微信端外支付 （调用微信h5支付+支付宝支付）
        if(this.activePayType == 1){  //微信h5支付
          this.wxH5Pay();
        }else{  //支付宝支付
          this.zfbPay();
        }
      }
    },
    zfbPay(){ //支付宝支付
      if (!this.activePayObj) return;
      let vipName = this.vipLevelName(this.activeLevel);
      let vipTitle = '抖音数据平台会员付费-' + vipName;
      let zfbPayPms = {
        OrderName: vipTitle,
        Duration: this.activePayObj.duration,
        VipType: this.activeLevel,
        MarketPrice: this.activePayObj.marketPrice,
        RatePrice: this.activePayObj.ratePrice,
        PayAmount: this.activePayObj.payAmount,
        // ReturnUrl: 'https://dy.zsjx114.com' + this.$route.path,
        ReturnUrl: location.href,
        TradeType: 'MWEB',  //微信支付方式  	NATIVE：手机扫码支付 JSAPI：公众号支付 APP：app支付 MWEB：H5支付
      }
      this.$axios
        .post('/api/pay/PayWapRequest', zfbPayPms)
        .then(res => {
          if (res.data.code == 0) {
            // this.$dialog.confirm({
            //   title: '请确认您的支付结果',
            //   cancelButtonText:'重新支付',
            //   confirmButtonText:'支付完成',
            // }).then(()=>{
            //   this.queryOrderStatus(this.orderId);  //查询订单状态
            // }).catch(()=>{
            //   this.zfbPay();
            // });
            this.orderId = res.data.data.orderId;
            location.href = res.data.data.url;
          }else{
            this.$toast(res.data.msg);
          }
        });
    },
    // 微信端内JSAPI支付
    wxJSAPIPay() {
      if (!this.activePayObj) return;
      let vipName = this.vipLevelName(this.activeLevel);
      let vipTitle = '抖音数据平台会员付费-' + vipName;
      let payPms = {
        OrderName: vipTitle,
        Duration: this.activePayObj.duration,
        VipType: this.activeLevel,
        MarketPrice: this.activePayObj.marketPrice,
        RatePrice: this.activePayObj.ratePrice,
        PayAmount: this.activePayObj.payAmount,
        ReturnUrl: location.href,
        TradeType: 'JSAPI',  //微信支付方式  	NATIVE：手机扫码支付 JSAPI：公众号支付 APP：app支付 MWEB：H5支付
      }
      this.$axios
        .post('/api/pay/WXPayRequest', payPms)
        .then(res => {
          if (res.data.code == 0) {
            this.orderDataObj = res.data.data;
            this.orderId = res.data.data.orderId;
            this.wxJSAPI(res.data.data);
            
          }else{
            this.$toast(res.data.msg);
          }
        });
    },
    // 微信端外H5支付
    wxH5Pay() {
      if (!this.activePayObj) return;
      let vipName = this.vipLevelName(this.activeLevel);
      let vipTitle = '抖音数据平台会员付费-' + vipName;
      let payPms = {
        OrderName: vipTitle,
        Duration: this.activePayObj.duration,
        VipType: this.activeLevel,
        MarketPrice: this.activePayObj.marketPrice,
        RatePrice: this.activePayObj.ratePrice,
        PayAmount: this.activePayObj.payAmount,
        ReturnUrl: location.href,
        TradeType: 'MWEB',  //微信支付方式  	NATIVE：手机扫码支付 JSAPI：公众号支付 APP：app支付 MWEB：H5支付
      }
      this.$axios
        .post('/api/pay/WXPayRequest', payPms)
        .then(res => {
          // console.log(res.data.data.url);
          if (res.data.code == 0) {
            this.orderId = res.data.data.orderId;
            location.href = res.data.data.url,'target';
          }else{
            this.$toast(res.data.msg);
          }
        });
    },
    payResultFn(){
      this.$dialog.confirm({
        title: '请确认您的支付结果',
        cancelButtonText:'重新支付',
        confirmButtonText:'支付完成',
      }).then(()=>{ // 确认支付成功，查询订单是否完成
        this.queryOrderStatus(this.orderId).then(()=>{
          location.href = location.origin + '/user';
        }).catch(()=>{
          this.$toast('支付未成功，请重新提交订单');
        });;
      }).catch(()=>{  //重新支付
        this.queryOrderStatus(this.orderId).then(()=>{
          this.$toast('该订单已支付成功');
          setTimeout(()=>{
            location.href = location.origin + '/user';
          },300);
        }).catch(()=>{
          this.$toast('支付未成功，请重新支付');
          setTimeout(()=>{
            this.wxJSAPI(this.orderDataObj);
          },300);
          // setTimeout(()=>{
          //   this.wxJSAPI(this.orderDataObj);
          // },200);
        });
      });
    },
    wxJSAPI(data){
      let that = this;
      if (typeof WeixinJSBridge == "undefined"){
        if( document.addEventListener ){
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        }else if (document.attachEvent){
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
      }else{
        onBridgeReady();
      }
      function onBridgeReady(){
        let {
          appid,
          timestamp,
          noncestr,
          prepayid,
          sign,
          paySign
        } = data;
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
              'debug':true,
              "appId":appid,     //公众号ID，由商户传入     
              "timeStamp":timestamp+'',         //时间戳，自1970年以来的秒数     
              "nonceStr":noncestr, //随机串     
              "package":"prepay_id="+prepayid,     
              "signType":"MD5",         //微信签名方式：     
              "paySign":paySign //微信签名 
            },
            function(res){
              that.payResultFn();
              // if(res.err_msg == "get_brand_wcpay_request:ok" ){
              //   // 使用以上方式判断前端返回,微信团队郑重提示：
              //   //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
              // } 
        });
      }
    },
    queryOrderStatus(oid){  //查询订单是否支付完成
      return new Promise((resolve, reject) => {
        this.$axios.get('/api/pay/GetOrderStatus',{
          params:{
            orderid:oid
          }
        })
        .then((res)=>{
          if(res.data.code == '0'){
            if(res.data.data.status == 1){ // 支付成功
              resolve()
            }else{
              reject()
            }
          }
        });
      })
    },
    comparisonVip(){
      let uLevel = this.initVipLevel(this.userLevel);
      this.btnDisabled = false;
      if(uLevel !== '' && uLevel){  //免费版和体验版都是立即开通
        let cLevel = this.initVipLevel(this.activeLevel);
        if(cLevel == uLevel){
          if(this.userLevel == '5' && this.userDetail.autoVipType != '0'){
            this.btnName = '您已是自动续费会员';
            this.btnDisabled = true;
          }else{
            this.btnName = '立即续费';
            this.btnDisabled = false;
          }
        }else if(cLevel > uLevel){
          this.btnName = '立即升级';
        }else{
          this.btnName = '您已是'+this.vipLevelName(this.userLevel);
          this.btnDisabled = true;
        }
      }else{  //免费版
        this.btnName = '立即开通';
      }
    },
    // 选择开通月份
    monthCheckedFn(itemObj) {
      if (itemObj.status) {
        this.monthIndex = itemObj.duration;
        this.activePayObj = itemObj;
      }
    },
    getUserInfo(){  //获取用户登录信息
      let uid = localStorage.getItem('user_id');
      if(uid){
        this.userDetail = {
          userId : uid,
          nickName : localStorage.getItem('nickName'),
          vipLevel : localStorage.getItem('vipLevel'),
          photo : localStorage.getItem('photo'),
          phone : localStorage.getItem('phone'),
          autoVipType : localStorage.getItem('autoVipType'),
        }
        this.userLevel = this.userDetail.vipLevel;
        this.comparisonVip();

        if(this.userDetail.vipLevel == 0){
          this.userDetail.vipEndTime1 = '免费版';
        }else{
          this.userDetail.vipEndTime1 = localStorage.getItem('vipEndTime1').split(' ')[0];
        }
      }
    },
    getMonthData(vipNum) {//获取月份数据
      let that = this;
      this.$axios(
        {
          method: 'get',
          url: 'api/pay/GetVipPrice',
          params: {
            VipType: vipNum ? vipNum : this.activeLevel,
            // VipData: this.value01,
          }
        },
        {
          cancelToken: new that.$axios.CancelToken(function executor(c) {
            if (that.cancelRequest) that.cancelRequest();
            that.cancelRequest = c;
          })
        }).then(res => {
          if (res.data.code == 0) {
            this.monthData = res.data.data;
            this.activePayObj = null;
            this.monthData.forEach(item => {
              if (this.monthIndex == item.duration && item.status) {
                //获取当前选中月份的支付结果
                this.activePayObj = item;
              }
            });
            this.comparisonVip();
          }
        });
    },    
    tabCheckedFn(level){
      this.monthIndex = 12;
      this.activeLevel = level;
      this.getMonthData(level);
    },
    initVipLevel(level){
      let aLevel = '';
      if(level == 3){
        aLevel = 0;
      }else if(level == 4){
        aLevel = 1;
      }else if(level == 5){
        aLevel = 2;
      }else if(level == 1){
        aLevel = 3;
      }else if(level == 2){
        aLevel = 4;
      }
      return aLevel;
    },
    vipLevelName(level){
      let name = '';
      if(level == 3){
        name = '体验版';
      }else if(level == 4){
        name = 'VIP-企业版';
      }else if(level == 1){
        name = 'SVIP-企业版';
      }else if(level == 2){
        name = 'Plus-企业版';
      }else if(level == 5){
        name = 'SVIP-个人版';
      }else{
         name = '免费版用户';
      }
      return name;
    },
    renewInit(dataObj){ //自定订阅相关判断展示
      if(dataObj.status == 1 && dataObj.vipType == dataObj.vipLevel){
        // status == 1说明存在自动续费会员等级（当前续费等级不一定是当前会员等级，必须加上 当前会员级别==自动续费会员等级），
        let dateStr = '';
        if(dataObj.duration == 1){
          dateStr = '月';
        }else if(dataObj.duration == 3){
          dateStr = '季';
        }else if(dataObj.duration == 12){
          dateStr = '年';
        }
        return '连续包'+dateStr;
      }
      return '';
    }
  },
  watch: {
    show(a){
      if(a){
        this.initUserLevel();
        this.monthIndex = 12;
        this.getUserInfo();
        this.getMonthData();
      }
    }
  }
};
</script>
<style lang='stylus' scoped>
@import './buyVipPopup.styl';
.vipPay_Popup{
  // z-index 1889 !important
  background-color transparent
  overflow-y: initial
}
</style>
